<template>
    <div>
      <el-upload
        class="upload-demo"
        action="fakeaction"
        :http-request="uploadSectionFile"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="image_dialog_visible" width="60%">
        <img :src="imageUrl" class="image_dialog">
      </el-dialog>
    </div>
</template>
<script>
export default {
  name: 'sFileImageAll',
  data () {
    return {
      fileList: [],
      image_dialog_visible: false, // 预览
      imageUrl: '' // 预览图片路径
    }
  },
  props: {
    // 图片路径
    image_list: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  watch: {
    image_list: function (val) { // 监听props中的属性
      this.fileList = val
    }
  },
  created () {
    this.imageUrl = this.image_list
  },
  methods: {
    handleRemove (file, fileList) {
      this.fileList = fileList
      this.$emit('confirm_imsge', fileList)
    },
    handlePreview (file) {
      this.imageUrl = file.url
      this.image_dialog_visible = true
    },
    uploadSectionFile (params) {
      const file = params.file
      const fileType = file.type
      const isImage = fileType.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      // 这里常规检验，看项目需求而定
      if (!isImage) {
        return this.$base.message({ type: 'error', that: this, message: '只能上传图片格式png、jpg、gif！' })
      }
      if (!isLt2M) {
        return this.$base.message({ type: 'error', that: this, message: '只能上传图片大小小于2M！' })
      }
      const data = new FormData()
      data.append('file', file)
      this.$base.request({
        that: this,
        method: 'POST',
        url: 'auth/upload/file_image',
        data: data
      }, (res) => {
        if (res.code === 8888) {
          this.fileList.push({
            id: res.data.image_id,
            name: res.data.url,
            url: res.data.url
          })
          this.$emit('confirm_imsge', this.fileList)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.image_dialog{
  width: 100%;
}
</style>
